package com.shop.www.JDBCUtils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.JdbcUtils;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtilsByDruid {
    private static DataSource ds;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    static {
        Properties properties = new Properties();
        try {
            properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("com\\shop\\www\\druid.properties"));
            /*properties.load(new FileInputStream("C:\\Users\\fxab\\Idea-Projects\\yidong\\src\\com\\shop\\www\\druid.properties"));*/
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if(connection==null) {
            connection = ds.getConnection();
            threadLocal.set(connection);
        }
        return threadLocal.get();

    }

    public static void close() throws SQLException {
        Connection conn = threadLocal.get();
        if(conn==null){
            return ;
        }
        if(!conn.isClosed()){
            conn.close();
            threadLocal.remove();
        }
    }
}